
#include "device_test.h"

#include <unistd.h>
#include <stdio.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "dump.h"

DeviceTest::DeviceTest()
    : mFd(-1)
    , mListener(NULL)
{
}

DeviceTest::~DeviceTest()
{
    std::list<TestCase*>::iterator it;
    for (it = mTestCases.begin(); it != mTestCases.end(); it++) {
        delete *it;
    }
    mTestCases.clear();
}

void DeviceTest::runCase(TestCase* tc)
{
    if (tc == NULL)
        return;

    int ret = write(mFd, tc->command.buffer(), tc->command.length());
    // printf("write %d bytes.\n", ret);
    // tools::dump(tc->command.buffer(), ret);

    unsigned char   buffer[10240] = {0};
    int             bytes_received = 0;

    while (bytes_received < tc->response.length()) {
        fd_set  rfds;
        FD_ZERO(&rfds);
        FD_SET(mFd, &rfds);
        struct timeval  tv;
        tv.tv_sec = 5;
        tv.tv_usec = 0;
        ret = select(mFd + 1, &rfds, NULL, NULL, &tv);
        if (ret <= 0) {
            break;
        }
        ret = read(mFd, buffer + bytes_received, 10240 - bytes_received);
        bytes_received += ret;
    }
    mListener->onTestCaseResult(tc->name.c_str(), (unsigned char *)tc->response.buffer(), tc->response.length(), buffer, bytes_received);
}

bool DeviceTest::runTest(const char * testName)
{
    if (mFd < 0)
        return false;

    if (mListener == NULL)
        return false;

    for (std::list<TestCase*>::iterator it = mTestCases.begin(); it != mTestCases.end(); it++) {
        TestCase * tc = *it;
        if (testName != NULL) {
            if (tc->name == testName) {
                runCase(tc);
                return true;
            }
        } else {
            runCase(tc);
        }
    }
    if (testName != NULL) {
        return false;
    }
    return true;
}

void DeviceTest::setFd(int fd)
{
    mFd = fd;
}

void DeviceTest::addTestCase(const char * name, unsigned char * command, int command_len, unsigned char * response, int response_len)
{
    TestCase * tc = new TestCase();
    tc->name = name;
    tc->command.assign((char *)command, command_len);
    tc->response.assign((char *)response, response_len);
    mTestCases.push_back(tc);
}


